#include "app/text.h"
#include "hardware/lcd.h"
#include "hardware/lcd_init.h"
#include "mid/printf.h"
#include "mid/ui.h"
#include "mid/widgets/button.h"
#include "mid/widgets/label.h"
#include "mid/widgets/window.h"

typedef struct MainWindow_t
{
    Label title;
    Label subTitle;
    Button btnFixedSpeed;
    Button btnFixedDistance;
    uint8_t bFixedSpeedSelected;
} MainWindow;

static MainWindow gMainWin;

void RenderMainWindow();

void UpdateMainWindow();

int OnButtonEvent(eButtonID btnID, eButtonEvent btnEvent);

Window* GetMainWindow()
{
    static Window window;
    window.Render = RenderMainWindow;
    window.Update = UpdateMainWindow;
    window.ProcessInput = OnButtonEvent;
    
    gMainWin.title = BuildLabel(LCD_W / 2, 30, TITLE, WHITE, BLUE);
    gMainWin.subTitle = BuildLabel(LCD_W / 2, 50, SUB_TITLE, WHITE, BLUE);

    gMainWin.bFixedSpeedSelected = 1;
    gMainWin.btnFixedSpeed = BuildButton(LCD_W / 2 - 50, LCD_H / 2 + 30, 50, 50, FIXED_SPEED, WHITE, BLUE);
    Select(&gMainWin.btnFixedSpeed, gMainWin.bFixedSpeedSelected);

    gMainWin.btnFixedDistance = BuildButton(LCD_W / 2 + 50, LCD_H / 2 + 30, 50, 50, FIXED_DISTANCE, WHITE, BLUE);
    Select(&gMainWin.btnFixedDistance, !gMainWin.bFixedSpeedSelected);

    return &window;
}

void RenderMainWindow()
{
    DrawLabel(&gMainWin.title);
    DrawLabel(&gMainWin.subTitle);
    RenderButton(&gMainWin.btnFixedSpeed);
    RenderButton(&gMainWin.btnFixedDistance);
}

void UpdateMainWindow()
{
}

void UpdateButtonState()
{
    Select(&gMainWin.btnFixedSpeed, gMainWin.bFixedSpeedSelected);
    Select(&gMainWin.btnFixedDistance, !gMainWin.bFixedSpeedSelected);
}

int OnButtonEvent(eButtonID btnID, eButtonEvent btnEvent)
{
    if (FLEX_BTN_PRESS_CLICK != btnEvent)
        return 0;

    switch (btnID)
    {
    case USER_BUTTON_LEFT:
        if (!gMainWin.bFixedSpeedSelected)
        {
            gMainWin.bFixedSpeedSelected = !gMainWin.bFixedSpeedSelected;
            UpdateButtonState();
        }
        break;
    
    case USER_BUTTON_RIGHT:
        if (gMainWin.bFixedSpeedSelected)
        {
            gMainWin.bFixedSpeedSelected = !gMainWin.bFixedSpeedSelected;
            UpdateButtonState();
        }
        break;

    case USER_BUTTON_MID:
        if (gMainWin.bFixedSpeedSelected)
            GetUIMgr()->EnterWindow(eWIN_FIX_SPEED);
        else
            GetUIMgr()->EnterWindow(eWIN_FIX_DISTANCE);
        break;

    default:
        return 0;
    }

    return 1;
}